<template>
  <div class="user-orders-container">
    <div class="user-layout">
      <!-- 侧边栏 -->
      <div class="sidebar">
        <UserSidebar />
      </div>
      
      <!-- 内容区 -->
      <div class="content">
        <div class="page-header">
          <h1>我的订单</h1>
          <p>查看并管理您的所有交易订单</p>
        </div>
        
        <el-card class="orders-card">
          <template #header>
            <div class="orders-card-header">
              <el-tabs v-model="activeTab" @tab-click="handleTabClick">
                <el-tab-pane label="全部订单" name="all"></el-tab-pane>
                <el-tab-pane label="待付款" name="unpaid"></el-tab-pane>
                <el-tab-pane label="进行中" name="processing"></el-tab-pane>
                <el-tab-pane label="已完成" name="completed"></el-tab-pane>
                <el-tab-pane label="已取消" name="cancelled"></el-tab-pane>
              </el-tabs>
              <div class="search-box">
                <el-input
                  v-model="searchKeyword"
                  placeholder="搜索订单号/车牌号"
                  @keyup.enter="searchOrders"
                  clearable
                >
                  <template #append>
                    <el-button @click="searchOrders">
                      <el-icon><Search /></el-icon>
                    </el-button>
                  </template>
                </el-input>
              </div>
            </div>
          </template>
          
          <!-- 订单列表 -->
          <div class="orders-list" v-loading="loading">
            <template v-if="orderList.length > 0">
              <div v-for="order in orderList" :key="order.id" class="order-item">
                <div class="order-header">
                  <div class="order-info">
                    <span class="order-number">订单号: {{ order.orderNumber }}</span>
                    <span class="order-time">创建时间: {{ formatDate(order.createTime) }}</span>
                  </div>
                  <div class="order-status">
                    <el-tag :type="getStatusType(order.status)">{{ getStatusText(order.status) }}</el-tag>
                  </div>
                </div>
                <div class="order-content">
                  <div class="car-info">
                    <el-image :src="order.carImage" class="car-image" fit="cover"></el-image>
                    <div class="car-details">
                      <h3 class="car-title">{{ order.carBrand }} {{ order.carModel }}</h3>
                      <p class="car-specs">{{ order.carYear }}年 | {{ order.carType }}</p>
                      <div class="price-info">
                        <span class="price">￥{{ order.price }}万</span>
                        <span class="total">总价: ￥{{ order.totalPrice }}万</span>
                      </div>
                    </div>
                  </div>
                  <div class="order-actions">
                    <div class="action-buttons">
                      <el-button 
                        type="primary" 
                        size="small" 
                        v-if="order.status === 'unpaid'"
                        @click="goToPay(order.id)"
                      >立即付款</el-button>
                      <el-button 
                        type="danger" 
                        size="small" 
                        v-if="['unpaid', 'processing'].includes(order.status)"
                        @click="cancelOrder(order.id)"
                      >取消订单</el-button>
                      <el-button 
                        type="success" 
                        size="small" 
                        v-if="order.status === 'completed'"
                        @click="reviewOrder(order.id)"
                      >评价</el-button>
                      <el-button 
                        type="info" 
                        size="small"
                        @click="viewOrderDetail(order.id)"
                      >查看详情</el-button>
                    </div>
                  </div>
                </div>
              </div>
            </template>
            
            <!-- 空状态 -->
            <el-empty v-else description="暂无订单数据">
              <template #description>
                <p>{{ getEmptyText() }}</p>
              </template>
              <el-button type="primary" @click="goCars">去浏览车辆</el-button>
            </el-empty>
          </div>
          
          <!-- 分页 -->
          <div class="pagination-container" v-if="total > 0">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[5, 10, 20, 50]"
              layout="total, sizes, prev, pager, next"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import UserSidebar from '../components/UserSidebar.vue'

const router = useRouter()
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const activeTab = ref('all')
const searchKeyword = ref('')

// 订单列表数据
const orderList = ref([
  // 模拟数据，实际应从API获取
  {
    id: 1,
    orderNumber: 'ORDER202304210001',
    createTime: '2023-04-21 15:30:22',
    status: 'unpaid',
    carBrand: '奔驰',
    carModel: 'C级 2023款',
    carYear: 2023,
    carType: '轿车',
    price: 32.98,
    totalPrice: 33.5,
    carImage: 'https://via.placeholder.com/300x200'
  },
  {
    id: 2,
    orderNumber: 'ORDER202304180002',
    createTime: '2023-04-18 09:15:36',
    status: 'processing',
    carBrand: '宝马',
    carModel: '3系 2022款',
    carYear: 2022,
    carType: '轿车',
    price: 29.8,
    totalPrice: 30.5,
    carImage: 'https://via.placeholder.com/300x200'
  },
  {
    id: 3,
    orderNumber: 'ORDER202304150003',
    createTime: '2023-04-15 14:22:10',
    status: 'completed',
    carBrand: '奥迪',
    carModel: 'A4L 2023款',
    carYear: 2023,
    carType: '轿车',
    price: 30.58,
    totalPrice: 31.2,
    carImage: 'https://via.placeholder.com/300x200'
  }
])

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  
  const date = new Date(dateStr.replace(' ', 'T'))
  const year = date.getFullYear()
  const month = (date.getMonth() + 1).toString().padStart(2, '0')
  const day = date.getDate().toString().padStart(2, '0')
  const hours = date.getHours().toString().padStart(2, '0')
  const minutes = date.getMinutes().toString().padStart(2, '0')
  
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

// 获取状态文字
const getStatusText = (status) => {
  const statusMap = {
    'unpaid': '待付款',
    'processing': '进行中',
    'completed': '已完成',
    'cancelled': '已取消'
  }
  return statusMap[status] || '未知状态'
}

// 获取状态对应的类型
const getStatusType = (status) => {
  const typeMap = {
    'unpaid': 'warning',
    'processing': 'primary',
    'completed': 'success',
    'cancelled': 'info'
  }
  return typeMap[status] || ''
}

// 获取空数据提示文字
const getEmptyText = () => {
  const textMap = {
    'all': '您目前没有任何订单',
    'unpaid': '您没有待付款的订单',
    'processing': '您没有进行中的订单',
    'completed': '您没有已完成的订单',
    'cancelled': '您没有已取消的订单'
  }
  return textMap[activeTab.value] || '暂无数据'
}

// 处理标签页点击
const handleTabClick = (tab) => {
  // 重置页码
  currentPage.value = 1
  // 重置搜索关键词
  searchKeyword.value = ''
  // 获取对应标签页的订单数据
  fetchOrders()
}

// 搜索订单
const searchOrders = () => {
  currentPage.value = 1
  fetchOrders()
}

// 改变每页条数
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchOrders()
}

// 改变页码
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchOrders()
}

// 前往付款
const goToPay = (orderId) => {
  router.push(`/payment?orderId=${orderId}`)
}

// 取消订单
const cancelOrder = (orderId) => {
  ElMessageBox.confirm('确定要取消该订单吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    loading.value = true
    // 模拟API调用
    setTimeout(() => {
      // 更新本地状态，实际应调用API
      const index = orderList.value.findIndex(item => item.id === orderId)
      if (index !== -1) {
        orderList.value[index].status = 'cancelled'
      }
      ElMessage.success('订单已取消')
      loading.value = false
    }, 500)
  }).catch(() => {
    // 用户取消操作
  })
}

// 查看订单详情
const viewOrderDetail = (orderId) => {
  router.push(`/order/detail/${orderId}`)
}

// 评价订单
const reviewOrder = (orderId) => {
  router.push(`/order/review/${orderId}`)
}

// 前往浏览车辆
const goCars = () => {
  router.push('/cars')
}

// 获取订单列表
const fetchOrders = () => {
  loading.value = true
  
  // 这里应该调用实际的API接口获取订单数据
  // 以下是模拟数据处理
  setTimeout(() => {
    // 根据标签页筛选数据
    let filteredOrders = [...orderList.value]
    
    if (activeTab.value !== 'all') {
      filteredOrders = filteredOrders.filter(order => order.status === activeTab.value)
    }
    
    // 搜索关键词筛选
    if (searchKeyword.value) {
      const keyword = searchKeyword.value.toLowerCase()
      filteredOrders = filteredOrders.filter(order => 
        order.orderNumber.toLowerCase().includes(keyword) || 
        order.carBrand.toLowerCase().includes(keyword) || 
        order.carModel.toLowerCase().includes(keyword)
      )
    }
    
    // 更新总数
    total.value = filteredOrders.length
    
    // 模拟分页
    const start = (currentPage.value - 1) * pageSize.value
    const end = start + pageSize.value
    orderList.value = filteredOrders.slice(start, end)
    
    loading.value = false
  }, 500)
}

// 初始化
onMounted(() => {
  fetchOrders()
})
</script>

<style lang="scss" scoped>
.user-orders-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  
  .user-layout {
    display: flex;
    gap: 20px;
    
    .sidebar {
      width: 250px;
      flex-shrink: 0;
    }
    
    .content {
      flex: 1;
      
      .page-header {
        margin-bottom: 20px;
        
        h1 {
          font-size: 24px;
          color: #333;
          margin-bottom: 8px;
        }
        
        p {
          color: #666;
          font-size: 14px;
          margin: 0;
        }
      }
    }
  }
  
  .orders-card {
    margin-bottom: 20px;
    
    .orders-card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .el-tabs {
        flex: 1;
      }
      
      .search-box {
        width: 300px;
      }
    }
  }
  
  .orders-list {
    .order-item {
      margin-bottom: 20px;
      border: 1px solid #ebeef5;
      border-radius: 4px;
      overflow: hidden;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .order-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 10px 15px;
        background-color: #f8f9fa;
        
        .order-info {
          .order-number {
            font-weight: bold;
            margin-right: 15px;
          }
          
          .order-time {
            color: #999;
            font-size: 14px;
          }
        }
      }
      
      .order-content {
        padding: 15px;
        display: flex;
        justify-content: space-between;
        
        .car-info {
          display: flex;
          
          .car-image {
            width: 120px;
            height: 80px;
            border-radius: 4px;
            margin-right: 15px;
          }
          
          .car-details {
            .car-title {
              margin: 0 0 5px 0;
              font-size: 16px;
            }
            
            .car-specs {
              margin: 0 0 10px 0;
              color: #666;
              font-size: 14px;
            }
            
            .price-info {
              .price {
                font-weight: bold;
                color: #f56c6c;
                font-size: 16px;
                margin-right: 10px;
              }
              
              .total {
                color: #999;
                font-size: 14px;
              }
            }
          }
        }
        
        .order-actions {
          display: flex;
          flex-direction: column;
          justify-content: center;
          
          .action-buttons {
            display: flex;
            flex-direction: column;
            gap: 8px;
          }
        }
      }
    }
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}

@media (max-width: 768px) {
  .user-orders-container {
    .user-layout {
      flex-direction: column;
      
      .sidebar {
        width: 100%;
      }
    }
    
    .orders-card {
      .orders-card-header {
        flex-direction: column;
        
        .search-box {
          width: 100%;
          margin-top: 15px;
        }
      }
      
      .order-content {
        flex-direction: column;
        
        .order-actions {
          margin-top: 15px;
          
          .action-buttons {
            flex-direction: row;
            flex-wrap: wrap;
          }
        }
      }
    }
  }
}
</style> 